package org.opens.javaskill.file;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 *
 * @author zym
 * @Date 2021/11/1 14:01
 */
public class ParseMakeFile {

    private static final String CONFIG_PATH = ".\\config.ini";

    @Test
    public void test1() {
        List<String> rows = null;
        Map<String, Map<String, String>> parseMap = new HashMap<>();
        String prefix = System.getProperty("user.dir") + "\\src\\test\\java\\org\\opens\\javaskill\\file\\";

        try {
            rows = FileUtils.readLines(new File(prefix, CONFIG_PATH), "utf-8");
            // 上下文缓存
            String key = "";
            for (int i = 0; i < rows.size(); i++) {
                // 去掉无效的空格
                String replaceEmptyRow = rows.get(i).replace(" ", "");

                // 设置上下文
                if (replaceEmptyRow.startsWith("[") && replaceEmptyRow.endsWith("]")) {
                    replaceEmptyRow = replaceEmptyRow.substring(1);
                    // 缓存上下文名称
                    key = replaceEmptyRow.substring(0, replaceEmptyRow.length() - 1);
                }

                // 跳过空白的[]
                if (StrUtil.isEmpty(key)) {
                    continue;
                }

                // 上下文key未初始化则先初始化
                if (!parseMap.containsKey(key)) {
                    parseMap.put(key, new HashMap<>());
                    continue;
                }

                // 跳过空行
                if (StrUtil.isEmpty(replaceEmptyRow)) {
                    continue;
                }

                // 跳过注释
                if (replaceEmptyRow.startsWith(";") || replaceEmptyRow.startsWith("#")) {
                    continue;
                }

                String[] splitRow = replaceEmptyRow.split("=");

                // 过滤空key
                if (StrUtil.isEmpty(splitRow[0])) {
                    continue;
                }

                if (splitRow.length >= 2) {
                    parseMap.get(key).put(splitRow[0], splitRow[1]);
                }
            }
            System.out.println(parseMap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
